from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. models import Types
from django.db.models import Q

from django.contrib.auth.decorators import permission_required

# Create your views here.


# 转到商品分类添加页面
@permission_required('myadmin.insert_types',raise_exception = True)
def typesadd(request):
	context = {'tlist':GetTypesAll()}
	return render(request,'admin/types/add.html',context)

# 执行 商品分类 添加
@permission_required('myadmin.insert_types',raise_exception = True)
def typesinsert(request):
	try:
		# 创建模型对象
		obj = Types()
		obj.pid = request.POST.get('pid')
		obj.name = request.POST.get('name')

		if obj.pid == '0':
			obj.path = '0,'
		else:
			# 如果不是添加的顶级分类，需要获取父类的path路径，再拼接上pid
			p = Types.objects.get(id=obj.pid)
			obj.path = p.path + str(obj.pid)+','
		obj.save()
		return HttpResponse('<script>alert("添加成功");location.href="/admin/types/list"</script>')
	except:
		return HttpResponse('<script>alert("添加失败");location.href="/admin/types/add"</script>')
		

# 分类列表
@permission_required('myadmin.show_types',raise_exception = True)
def typeslist(request):

	# 获取搜索类型
	types = request.GET.get('types')
	# 获取搜索关键字
	keywords = request.GET.get('keywords')


	if types:
		# 有搜索类型
		if types == 'all':
			data = Types.objects.filter(Q(id__contains=keywords)|Q(name__contains=keywords)|Q(path__contains=keywords))
			data = data | getPidTypes(keywords)
		elif types == 'id':
			data = Types.objects.filter(id__contains=keywords)
		elif types == 'name':
			data = Types.objects.filter(name__contains=keywords)
		elif types == 'pname':
			# 将pname转成pid,找到父类型数据
			
			# 新建空集合
			data = Types.objects.none()
			objs = Types.objects.filter(name__contains=keywords)
			if objs.exists():
				for x in objs:
					pid = x.id
					if pid:
						data1 = Types.objects.filter(pid__contains=pid)
						data = data | data1
			else:
				data = objs

			# 搜索关键字含有 顶级分类 时，增加数据
			if keywords in '顶级分类':
				data0 = Types.objects.filter(pid='0')
				data = data | data0
	
		elif types == 'path':
			data = Types.objects.filter(path__contains=keywords)
		

		data = orderTypes(data)
	else:
		# 没有搜索类型，全部显示
		data = GetTypesAll()



	# 数据分页
	from django.core.paginator import Paginator
	# 实例化分页类 参数1-参数的数据，参数2-每页显示的数据
	paginator = Paginator(data,5)
	# 当前页码
	p = int(request.GET.get('p',1))
	# 根据当前页码获取当前页码应该显示的数据
	tlist = paginator.page(p)
	# 获取当前页的页码数
	num = paginator.page_range
	
	context = {'tlist':tlist,'pagenum':num}
	return render(request,'admin/types/list.html',context)

# 编辑
@permission_required('myadmin.edit_types',raise_exception = True)
def typesedit(request,tid):
	# 根据tid获取当前数据对象
	obj = Types.objects.get(id=tid)
	context = {'tinfo':obj,'tlist':GetTypesAll()}
	return render(request,'admin/types/edit.html',context)

# 执行更新
@permission_required('myadmin.edit_types',raise_exception = True)
def typesupdate(request):
	tid = request.POST.get('tid')
	try:
		obj = Types.objects.get(id = tid)
		# obj.pid = request.POST.get('pid') #页面中的pid不能进行修改
		obj.name = request.POST.get('name')
		obj.save()
		return HttpResponse('<script>alert("修改成功");location.href="/admin/types/list"</script>')
	except:
		return HttpResponse('<script>alert("修改失败");location.href="/admin/types/edit/'+str(tid)+'"</script>')


# 删除 商品分类
@permission_required('myadmin.del_types',raise_exception = True)
def typesdel(request):
	# 获取要删除对象的id
	tid = request.GET['tid']
	# 查看当期类型下 是否有子类型 count()-返回当前查询的总条数
	num = Types.objects.filter(pid=tid).count()
	# 判断是否有子类
	if num:
		return JsonResponse({'status':1,'msg':'当前类型下还有子类，不能删除'})
	# 没有子类时
	obj = Types.objects.get(id=tid)
	obj.delete()
	return JsonResponse({'status':0,'msg':'可以删除'})





# 获取所有的分类 并排序
def GetTypesAll():
	# 获取所有的商品分类
	# obj = Types.objects.all()
	# select * ,concat(path,id) as paths from myadmin_types order by paths;
	ob = Types.objects.extra(select={'paths':'concat(path,id)'}).order_by('paths')

	for x in ob:
		# 控制当前对象的 缩进
		n = int(len(x.path)/2)-1
		x.name = (n*'|----')+ x.name
		# 给当前对象 添加一个所属父类的属性
		if x.pid == 0:
			x.pname='顶级分类'
		else:
			obj = Types.objects.get(id=x.pid)
			x.pname = obj.name

	return ob


# 排序 查询后的对象
def orderTypes(obj_arg):
	ob = obj_arg.extra(select={'paths':'concat(path,id)'}).order_by('paths')

	for x in ob:
		n = int(len(x.path)/2)-1
		x.name = (n*'|----')+x.name
		if x.pid == 0:
			x.pname = '顶级分类'
		else:
			obj= Types.objects.get(id=x.pid)
			x.pname = obj.name

	return ob


# 查询所属分类数据
def getPidTypes(keywords):
	keywords = keywords
	data = Types.objects.none()
	objs = Types.objects.filter(name__contains=keywords)
	if objs.exists():
		for x in objs:
			pid = x.id
			if pid:
				data1 = Types.objects.filter(pid__contains=pid)
				data = data | data1
	else:
		data = objs

	# 搜索关键字含有 顶级分类 时，增加数据
	if keywords in '顶级分类':
		data0 = Types.objects.filter(pid='0')
		data = data | data0

	return data

